package com.chatplus.application.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import com.chatplus.application.common.constant.RedisPrefix;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.AdminConfigDto;
import com.chatplus.application.domain.request.SendSmsRequest;
import com.chatplus.application.service.verification.PlusCaptchaService;
import com.chatplus.application.util.ConfigUtil;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信验证码服务
 */
@RestController
@Validated
@RequestMapping("/api/sms")
public class SmsApiController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(SmsApiController.class);
    private final RedissonClient redissonClient;

    private static final String CAPTCHA_REDIS_KEY = RedisPrefix.TURN_RIGHT_REDIS_PREFIX + "captcha:botCaptcha:";

    @Autowired
    public SmsApiController(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 发送手机短信验证码
     *
     * @return boolean
     */
    @PostMapping("/code")
    @SaIgnore
    public boolean code(@RequestBody @Valid SendSmsRequest sendSmsRequest) {
        AdminConfigDto adminConfigDto = ConfigUtil.getAdminConfig();
        if (adminConfigDto.isEnabledBotValidate()) {
            if (StringUtils.isEmpty(sendSmsRequest.getKey())) {
                throw new BadRequestException("请进行人机校验");
            }
            RBucket<Boolean> rBucket = redissonClient.getBucket(CAPTCHA_REDIS_KEY + sendSmsRequest.getKey());
            boolean success = rBucket.isExists() && rBucket.get();
            if (!success) {
                throw new BadRequestException("请进行人机校验");
            }
        }
        String receiver = sendSmsRequest.getReceiver();
        PlusCaptchaService plusCaptchaService = PlusCaptchaService.getInstance(receiver);
        return plusCaptchaService.sendCaptcha(sendSmsRequest.getReceiver());
    }
}
